package com.sky.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.service.SetMealDishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.ResultExtractor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.WebEndpoint;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@Api(tags = "菜品管理")
@RequestMapping("/admin/dish")
public class DishController {


    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetMealDishService setMealDishService;
    @Autowired
    private SetmealDishMapper setmealDishMapper;


    /**
     *
     * @param dishDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增菜品")
    @Transactional
    public Result add(@RequestBody DishDTO dishDTO){

        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO,dish);
        dishService.save(dish);

        if(dishDTO.getFlavors() != null){
        List<DishFlavor> flavors = dishDTO.getFlavors();
        Long dishId = dish.getId();

        flavors = flavors.stream().map((item -> {
            item.setDishId(dishId);
            return item;
        })).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
        }
        return Result.success();
    }




    /**
     *
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public Result queryPage(DishPageQueryDTO dishPageQueryDTO){

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(dishPageQueryDTO.getName() != null,Dish::getName,dishPageQueryDTO.getName());
        lambdaQueryWrapper.eq(dishPageQueryDTO.getCategoryId() != null,Dish::getCategoryId,dishPageQueryDTO.getCategoryId());
        lambdaQueryWrapper.eq(dishPageQueryDTO.getStatus() != null,Dish::getStatus,dishPageQueryDTO.getStatus());
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);


        Page<Dish> dishPage = dishService.page(new Page<>(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize()), lambdaQueryWrapper);

        Page<DishVO> pageVo = new Page<>();


        BeanUtils.copyProperties(dishPage,pageVo,"records");
        List<Dish> records = dishPage.getRecords();

        List<DishVO> voList = records.stream().map((item) -> {
            DishVO dishVO = new DishVO();

            BeanUtils.copyProperties(item, dishVO);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null) {
                String categoryName = category.getName();
                dishVO.setCategoryName(categoryName);
            }
            return dishVO;
        }).collect(Collectors.toList());


        pageVo.setRecords(voList);


        return Result.success(pageVo);
    }

    /**
     * 根据id查询（回显）
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "页面回显")
    public Result<DishVO> selectId(@PathVariable Long id){
        log.info("回显页面信息");
        Dish dish = dishService.getById(id);
        List<DishFlavor> dishFlavor = dishFlavorService.lambdaQuery()
                .eq(DishFlavor::getDishId,id)
                .list();
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavor);

        return Result.success(dishVO);
    }

    /**
     * TODO 待完成
     * @param dishDTO
     * @return
     */
    @PutMapping
    @ApiOperation("编辑菜品")
    public Result update(@RequestBody DishDTO dishDTO){

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishService.updateById(dish);

        Dish removeId = dishService.getById(dishDTO.getId());
        List<DishFlavor> list = dishFlavorService.lambdaQuery()
                .eq(DishFlavor::getDishId, removeId.getId())
                .list();
        if (list != null) {
            dishFlavorService.removeBatchByIds(list);
        }
        if(dishDTO.getFlavors() != null){
            List<DishFlavor> flavors = dishDTO.getFlavors();
            Long id = dishDTO.getId();

            flavors.stream().map((item)->{
                item.setDishId(id);
                return item;
            }).collect(Collectors.toList());
            dishFlavorService.saveBatch(flavors);

        }


        return Result.success();

    }
    @PostMapping("/status/{status}")
    @ApiOperation("启用停用")
    public Result startOrStop(@PathVariable Integer status , Long id){
        Dish dish = dishService.getById(id);
        dish.setStatus(status);
        dishService.updateById(dish);
        return Result.success();
    }


    @DeleteMapping
    @ApiOperation("删除菜品")
    public Result removeBatch(@RequestParam List<Long> ids){
        ids.stream().map((item) -> {
            Dish dish = dishService.getById(item);
            if (dish.getStatus() == StatusConstant.DISABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            return dish;
        }).collect(Collectors.toList());


        List<SetmealDish> list = setmealDishMapper.selectBatchIds(ids);
        if (list.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        dishService.removeBatchByIds(ids);
        return Result.success();

    }

    @GetMapping("/list")
    @ApiOperation(value = "添加菜品")
    public Result<List> list(Long categoryId){
        List<Dish> list = dishService.lambdaQuery()
                .eq(Dish::getCategoryId,categoryId)
                .list();
        return Result.success(list);
    }


}
